package org.hbgl.geoentity.admin.vo;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.hbgl.geoentity.db.domain.DicTrade;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代码功能：
 * 开发日期：2022/5/11
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
@Data
public class TradeVo {
    private Integer id;
    private Integer pid;
    private String name;
    private List<TradeVo> children;

    /**
     * 使⽤递归⽅法建树
     *
     * @param list 行政区划列表
     * @return 树
     */
    public static List<TradeVo> build(List<DicTrade> list) {
        List<TradeVo> trees = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return trees;
        }
        Integer pidMin = list.stream().mapToInt(DicTrade::getParentId).summaryStatistics().getMin();
        List<DicTrade> listMin = list.stream().filter(p -> p.getParentId().equals(pidMin)).collect(Collectors.toList());
        for (DicTrade item : listMin) {
            TradeVo parent = new TradeVo();
            parent.setId(item.getId());
            parent.setPid(item.getParentId());
            parent.setName(item.getTradeName());
            findChild(parent, list);
            trees.add(parent);
        }
        return trees;
    }

    private static TradeVo findChild(TradeVo parent, List<DicTrade> list) {
        for (DicTrade item : list) {
            TradeVo child = new TradeVo();
            child.setId(item.getId());
            child.setPid(item.getParentId());
            child.setName(item.getTradeName());

            if (parent.getId().equals(child.getPid())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChild(child, list));
            }
        }
        return parent;
    }
}
